package com.sanchunhui.psc.ui.activity

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.PersistableBundle
import android.util.Log
import com.alibaba.android.arouter.launcher.ARouter
import com.bigkoo.alertview.AlertView
import com.bigkoo.alertview.OnItemClickListener
import com.sanchunhui.psc.common.BaseApplication
import com.sanchunhui.psc.injection.component.ActivityComponent
import com.sanchunhui.psc.injection.component.DaggerActivityComponent
import com.sanchunhui.psc.injection.module.ActivityModule
import com.sanchunhui.psc.injection.module.LifecycleProviderModule
import com.sanchunhui.psc.presenter.BasePresenter
import com.sanchunhui.psc.presenter.view.BaseView
import com.sanchunhui.psc.widgets.ProgressLoading
import org.devio.takephoto.R
import org.devio.takephoto.app.TakePhoto
import org.devio.takephoto.app.TakePhotoImpl
import org.devio.takephoto.compress.CompressConfig
import org.devio.takephoto.model.*
import org.devio.takephoto.permission.InvokeListener
import org.devio.takephoto.permission.PermissionManager
import org.jetbrains.anko.toast
import java.io.File
import javax.inject.Inject

/*
    存在选择图片的Activity基础封装
 */
abstract open class BaseTakePhotoActivity<T : BasePresenter<*>> : BaseActivity(), BaseView, TakePhoto.TakeResultListener , InvokeListener {

    private lateinit var mTakePhoto:TakePhoto
    private var invokeParam: InvokeParam? = null

    private lateinit var mTempFile: File

    @Inject
    lateinit var mPresenter: T
    lateinit var mActivityComponent: ActivityComponent

    private lateinit var mLoadingDialog: ProgressLoading

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initActivityInjection()
        injectComponent()

        mTakePhoto = TakePhotoImpl(this,this)
        mTakePhoto.onCreate(savedInstanceState)

        mLoadingDialog = ProgressLoading.create(this)
        ARouter.getInstance().inject(this)
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        mTakePhoto.onSaveInstanceState(outState)
        super.onSaveInstanceState(outState, outPersistentState)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        val type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this)
    }


    /*
        Dagger注册
     */
    protected abstract fun injectComponent()

    /*
        初始化Activity Component
     */
    private fun initActivityInjection() {
        mActivityComponent = DaggerActivityComponent.builder().appComponent((application as BaseApplication).appComponent)
                .activityModule(ActivityModule(this))
                .lifecycleProviderModule(LifecycleProviderModule(this))
                .build()

    }

    /*
        显示加载框，默认实现
     */
    override fun showLoading() {
        mLoadingDialog.showLoading()
    }

    /*
        隐藏加载框，默认实现
     */
    override fun hideLoading() {
        mLoadingDialog.hideLoading()
    }

    /*
        错误信息提示，默认实现
     */
    override fun onError(text:String) {
        toast(text)
    }

    /*
        弹出选择框，默认实现
        可根据实际情况，自行修改
     */
    protected fun showAlertView() {

        mTempFile = File(
            Environment.getExternalStorageDirectory(),
            "/temp/" + System.currentTimeMillis() + ".jpg"
        )
        if (!mTempFile.parentFile.exists()) {
            mTempFile.parentFile.mkdirs()
        }
        val imageUri = Uri.fromFile(mTempFile)

        configCompress()
        configTakePhotoOption()

        AlertView("选择图片", "", "取消", null, arrayOf("相册"), this,
            AlertView.Style.ActionSheet, OnItemClickListener { o, position ->
                mTakePhoto.onEnableCompress(CompressConfig.ofDefaultConfig(),false)
                when (position) {

                    0 ->{

                        // 从相册选择
                        val limitNum : Int = 1
                        if (limitNum > 1) {
                            mTakePhoto.onPickMultipleWithCrop(limitNum, getCropOptions()) //裁切
                            //选择多张图片时会自动切换到TakePhoto自带相册
//                        mTakePhoto.onPickMultiple(limitNum)  //最多选择5张，不裁切
                            return@OnItemClickListener
                        }
                        mTakePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions()) //裁切
//                    mTakePhoto.onPickFromGallery() //不裁切
                    }

                }
            }

        ).show()

//        AlertView("选择图片", "", "取消", null, arrayOf("拍照", "相册"), this,
//                AlertView.Style.ActionSheet, OnItemClickListener { o, position ->
//            mTakePhoto.onEnableCompress(CompressConfig.ofDefaultConfig(),false)
//            when (position) {
//                0 -> {
//                    // 拍照
//                    mTakePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions()) // 剪切
////                    mTakePhoto.onPickFromCapture(imageUri) // 不剪切
//                }
//                1 ->{
//
//                    // 从相册选择
//                    val limitNum : Int = 1
//                    if (limitNum > 1) {
//                        mTakePhoto.onPickMultipleWithCrop(limitNum, getCropOptions()) //裁切
//                        //选择多张图片时会自动切换到TakePhoto自带相册
////                        mTakePhoto.onPickMultiple(limitNum)  //最多选择5张，不裁切
//                        return@OnItemClickListener
//                    }
//                    mTakePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions()) //裁切
////                    mTakePhoto.onPickFromGallery() //不裁切
//                }
//
//            }
//        }
//
//        ).show()

    }

    /*
        获取图片，成功回调
     */
    override fun takeSuccess(result: TResult?) {
        Log.d("TakePhoto",result?.image?.originalPath)
        Log.d("TakePhoto",result?.image?.compressPath)
    }

    /*
        获取图片，取消回调
     */
    override fun takeCancel() {
        Log.i("", resources.getString(R.string.msg_operation_canceled))
    }

    override fun invoke(invokeParam: InvokeParam): PermissionManager.TPermissionType {
        val type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.method)
        if (PermissionManager.TPermissionType.WAIT == type) {
            this.invokeParam = invokeParam
        }
        return type
    }

    /*
        获取图片，失败回调
     */
    override fun takeFail(result: TResult?, msg: String?) {
        Log.e("takePhoto",msg)
    }

    /*
        TakePhoto默认实现
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mTakePhoto.onActivityResult(requestCode,resultCode,data)
    }

    /*
        新建临时文件
     */
    fun createTempFile(){
//        val tempFileName = "/temp/${System.currentTimeMillis()}.jpg"
//        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
//            this.mTempFile = File(Environment.getExternalStorageDirectory(),tempFileName)
//            return
//        }
//
//        this.mTempFile = File(filesDir,tempFileName)
    }


    /*
      压缩配置
     */
    private fun configCompress() {
//        if (rgCompress.getCheckedRadioButtonId() != R.id.rbCompressYes) {
//            takePhoto.onEnableCompress(null, false)
//            return
//        }
        val maxSize = 102400 // 大小不超过
        val width = 800 // 宽
        val height = 800 // 高
        val showProgressBar = true // 是否显示压缩进度
        val enableRawFile = true // 拍照压缩后是否保存原图
        val config: CompressConfig
        // 压缩工具自带
        config = CompressConfig.Builder().setMaxSize(maxSize)
            .setMaxPixel(if (width >= height) width else height)
            .enableReserveRaw(enableRawFile)
            .create()
        // Luban压缩工具
//        val option = LubanOptions.Builder().setMaxHeight(height).setMaxWidth(width).setMaxSize(maxSize)
//                .create()
//        config = CompressConfig.ofLuban(option)
//        config.enableReserveRaw(enableRawFile)
        mTakePhoto.onEnableCompress(config, showProgressBar)
    }

    /*
    选择图片配置
     */
    private fun configTakePhotoOption() {
        val builder = TakePhotoOptions.Builder()
        builder.setWithOwnGallery(true) //使用TakePhoto自带相册：
        builder.setCorrectImage(true) //纠正拍照的照片旋转角度：
        mTakePhoto.setTakePhotoOptions(builder.create())

    }

    private fun getCropOptions(): CropOptions? {

        // 尺寸比例
        val height = 800
        val width = 800
        // 裁切工具
        val withWonCrop = false //false 第三方， true TakePhoto自带

        val builder = CropOptions.Builder()
        builder.setOutputX(width).setOutputY(height)
//        builder.setAspectX(width).setAspectY(height)  // 定制宽高

        builder.setWithOwnCrop(withWonCrop)
        return builder.create()
    }
}
